
package com.dny.asmtop;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * java接触类型封装
 * @author Administrator
 */
public final class Primitives {
  private static final Map<Class<?>, Class<?>> PRIMITIVE;
  private static final Map<Class<?>, Class<?>> WRAPPER;

  private Primitives() {
  }

  static {
    Map<Class<?>, Class<?>> primToWrap = new HashMap<>();
    Map<Class<?>, Class<?>> wrapToPrim = new HashMap<>();

    add(primToWrap, wrapToPrim, Boolean.TYPE, Boolean.class);
    add(primToWrap, wrapToPrim, Byte.TYPE, Byte.class);
    add(primToWrap, wrapToPrim, Character.TYPE, Character.class);
    add(primToWrap, wrapToPrim, Double.TYPE, Double.class);
    add(primToWrap, wrapToPrim, Float.TYPE, Float.class);
    add(primToWrap, wrapToPrim, Integer.TYPE, Integer.class);
    add(primToWrap, wrapToPrim, Long.TYPE, Long.class);
    add(primToWrap, wrapToPrim, Short.TYPE, Short.class);
    add(primToWrap, wrapToPrim, Void.TYPE, Void.class);

    PRIMITIVE = Collections.unmodifiableMap(primToWrap);
    WRAPPER = Collections.unmodifiableMap(wrapToPrim);
  }

  private static void add(Map<Class<?>, Class<?>> forward, Map<Class<?>, Class<?>> backward, Class<?> key, Class<?> value) {
    forward.put(key, value);
    backward.put(value, key);
  }

  public static Set<Class<?>> allPrimitiveTypes() {
    return PRIMITIVE.keySet();
  }

  public static Set<Class<?>> allWrapperTypes() {
    return WRAPPER.keySet();
  }

  public static boolean isWrapperType(Class<?> type) {
    if (type == null) {
      throw new NullPointerException();
    }
    return WRAPPER.containsKey(type);
  }

  public static <T> Class<T> wrap(Class<T> type) {
    if (type == null) {
      throw new NullPointerException();
    }
    Class<T> wrapped = (Class<T>) PRIMITIVE.get(type);
    return wrapped == null ? type : wrapped;
  }

  public static <T> Class<T> unwrap(Class<T> type) {
    if (type == null) {
      throw new NullPointerException();
    }
    Class<T> unwrapped = (Class<T>) WRAPPER.get(type);
    return unwrapped == null ? type : unwrapped;
  }
}
